package com.bq.gametrade.view;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bq.gametrade.GameTradeApplication;
import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.activity.ForgetPayPasswordActivity;
import com.bq.gametrade.ui.activity.LoginActivity;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.ui.dialog.PayFailureDialog;
import com.bq.gametrade.utils.MD5Util;
import com.bq.gametrade.utils.SharedPreferencesUtils;
import com.bq.gametrade.utils.ToastUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Feel on 2017/1/11.
 */

public class PayPasswordValidationView extends PopupWindow implements View.OnClickListener {

    private Activity activity;
    private LoadingProgressDialog dialog;
    private LinearLayout layKeyBoard, keyBoardDelete;
    private TextView keyBoardOne, keyBoardTwo, keyBoardThree, keyBoardFour, keyBoardFive, keyBoardSix, keyBoardSeven, keyBoardEight, keyBoardNine, keyBoardZero;

    private ImageView imgDismiss;

    private LinearLayout layPassword;

    private TextView[] tvList;      //用数组保存6个TextView，为什么用数组？

    private ImageView[] imgList;      //用数组保存6个TextView，为什么用数组？

    private TextView tvPayContent;

    private TextView tvForgetPassword;

    private UserInfoDetails userInfo;


    private int currentIndex = -1;    //用于记录当前输入密码格位置
    private int errorCount = 0;

//    private String payTitle,payMoneyCount;
//    private int payType;

    /**
     * 回调
     */
    public interface OnPayPasswordInputFinish {
        void inputFinish(String status);
    }


    public PayPasswordValidationView(Activity context, UserInfoDetails userInfo,LoadingProgressDialog dialog) {
        super(context);
        this.activity = context;
        this.userInfo = userInfo;
        this.dialog = dialog;
        View view = LayoutInflater.from(activity).inflate(R.layout.view_popwindow_paypassword, null);
        this.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        this.setHeight(ActionBar.LayoutParams.WRAP_CONTENT);
        this.setContentView(view);
        this.setAnimationStyle(R.style.PayPasswordPopAnimation);
        this.setFocusable(false);
        this.setOutsideTouchable(false);
        this.setBackgroundDrawable(new ColorDrawable(0x00000000));
        initView(view);
        initKeyBoardView(view);


    }

    private void initView(View view) {


        tvList = new TextView[6];
        imgList = new ImageView[6];
        tvList[0] = (TextView) view.findViewById(R.id.tv_pass1);
        tvList[1] = (TextView) view.findViewById(R.id.tv_pass2);
        tvList[2] = (TextView) view.findViewById(R.id.tv_pass3);
        tvList[3] = (TextView) view.findViewById(R.id.tv_pass4);
        tvList[4] = (TextView) view.findViewById(R.id.tv_pass5);
        tvList[5] = (TextView) view.findViewById(R.id.tv_pass6);

        imgList[0] = (ImageView) view.findViewById(R.id.img_pass1);
        imgList[1] = (ImageView) view.findViewById(R.id.img_pass2);
        imgList[2] = (ImageView) view.findViewById(R.id.img_pass3);
        imgList[3] = (ImageView) view.findViewById(R.id.img_pass4);
        imgList[4] = (ImageView) view.findViewById(R.id.img_pass5);
        imgList[5] = (ImageView) view.findViewById(R.id.img_pass6);


    }


    private void initKeyBoardView(View view) {

        imgDismiss = (ImageView) view.findViewById(R.id.iv_popDismiss);
        imgDismiss.setOnClickListener(this);
        layPassword = (LinearLayout) view.findViewById(R.id.lay_password);
        layPassword.setOnClickListener(this);

        tvForgetPassword = (TextView) view.findViewById(R.id.tv_forgetPayPassword);
        tvForgetPassword.setOnClickListener(this);


        layKeyBoard = (LinearLayout) view.findViewById(R.id.lay_keyBoard);
        keyBoardDelete = (LinearLayout) view.findViewById(R.id.lay_keyBoardDelete);
        keyBoardDelete.setOnClickListener(this);

        keyBoardOne = (TextView) view.findViewById(R.id.tv_numOne);
        keyBoardOne.setOnClickListener(this);
        keyBoardTwo = (TextView) view.findViewById(R.id.tv_numTwo);
        keyBoardTwo.setOnClickListener(this);
        keyBoardThree = (TextView) view.findViewById(R.id.tv_numThree);
        keyBoardThree.setOnClickListener(this);
        keyBoardFour = (TextView) view.findViewById(R.id.tv_numFour);
        keyBoardFour.setOnClickListener(this);
        keyBoardFive = (TextView) view.findViewById(R.id.tv_numFive);
        keyBoardFive.setOnClickListener(this);
        keyBoardSix = (TextView) view.findViewById(R.id.tv_numSix);
        keyBoardSix.setOnClickListener(this);
        keyBoardSeven = (TextView) view.findViewById(R.id.tv_numSeven);
        keyBoardSeven.setOnClickListener(this);
        keyBoardEight = (TextView) view.findViewById(R.id.tv_numEight);
        keyBoardEight.setOnClickListener(this);
        keyBoardNine = (TextView) view.findViewById(R.id.tv_numNine);
        keyBoardNine.setOnClickListener(this);
        keyBoardZero = (TextView) view.findViewById(R.id.tv_numZero);
        keyBoardZero.setOnClickListener(this);


    }

    private boolean isShowKeyBoard = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_popDismiss:
                dismiss();
                break;
            case R.id.tv_forgetPayPassword:
                activity.startActivity(new Intent(activity, ForgetPayPasswordActivity.class));
                break;
            case R.id.lay_keyBoardDelete:
                delete();
                break;
            case R.id.tv_numZero:
                initResult(keyBoardZero.getText().toString());
                break;
            case R.id.tv_numOne:
                initResult(keyBoardOne.getText().toString());
                break;
            case R.id.tv_numTwo:

                initResult(keyBoardTwo.getText().toString());
                break;
            case R.id.tv_numThree:

                initResult(keyBoardThree.getText().toString());
                break;
            case R.id.tv_numFour:

                initResult(keyBoardFour.getText().toString());
                break;
            case R.id.tv_numFive:
                initResult(keyBoardFive.getText().toString());
                break;
            case R.id.tv_numSix:
                initResult(keyBoardSix.getText().toString());
                break;
            case R.id.tv_numSeven:
                initResult(keyBoardSeven.getText().toString());
                break;
            case R.id.tv_numEight:
                initResult(keyBoardEight.getText().toString());
                break;
            case R.id.tv_numNine:
                initResult(keyBoardNine.getText().toString());
                break;

        }

    }


    private void initResult(String text) {
        if (currentIndex >= -1 && currentIndex < 5) {      //判断输入位置————要小心数组越界
            ++currentIndex;
            tvList[currentIndex].setText(text);
            tvList[currentIndex].setVisibility(View.INVISIBLE);
            imgList[currentIndex].setVisibility(View.VISIBLE);
        }
    }

    private void delete() {
        if (currentIndex - 1 >= -1) {//判断是否删除完毕————要小心数组越界
            tvList[currentIndex].setText("");
            tvList[currentIndex].setVisibility(View.VISIBLE);
            imgList[currentIndex].setVisibility(View.INVISIBLE);
            currentIndex--;
        }

    }
    private void clearPasswords(){
        for (int i = 0; i < 6; i++) {
            tvList[i].setText("");
            imgList[i].setVisibility(View.INVISIBLE);
        }
        currentIndex = -1;
    }

    public void setOnFinishInputPayPassword(final OnPayPasswordInputFinish onPayPasswordInputFinish) {
        tvList[5].addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() == 1) {

                    String strPassword = "";     //每次触发都要先将strPassword置空，再重新获取，避免由于输入删除再输入造成混乱

                    for (int i = 0; i < 6; i++) {
                        strPassword += tvList[i].getText().toString().trim();
                    }
                    validationPayPassword(strPassword,onPayPasswordInputFinish); //接口中要实现的方法，完成密码输入完成后的响应逻辑
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);

    }

    private void validationPayPassword(String password,final OnPayPasswordInputFinish passwordInputFinish) {
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("pay_pwd", MD5Util.md5(password));
        dialog.show();
        VRHttp.sendRequest(activity, HttpLink.VALIDATION_PAYPASSWORD_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        passwordInputFinish.inputFinish(bean.status);    //接口中要实现的方法，完成密码输入完成后的响应逻辑
                        dismiss();
                        SharedPreferencesUtils.saveValue(activity,SharedPreferencesUtils.pay_errorCount,0);
                    } else if(bean.status.equals("1")){
                        int errorCount = (Integer) SharedPreferencesUtils.getValue(activity,SharedPreferencesUtils.pay_errorCount,0);
                        errorCount++;
                        new PayFailureDialog(activity).builder().setTouchOutsideCanceled(false).setCancelable(true)
                                .setMsg("支付密码不正确，已经输入错误"+errorCount+"次")
                                .setPositiveButton("忘记密码",new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        activity.startActivity(new Intent(activity,ForgetPayPasswordActivity.class));
                                    }
                                }).setNegativeButton("重新输入",new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                clearPasswords();
                            }
                        }).show();
                        SharedPreferencesUtils.saveValue(activity,SharedPreferencesUtils.pay_errorCount,errorCount);
                    }else if (bean.status.equals("99")) {
                        dialog.dismiss();
                        dismiss();
                        ToastUtils.showToast(activity, "登录超时请重新登陆");
                        activity.startActivity(new Intent(activity, LoginActivity.class));
                    } else if (bean.status.equals("98")) {
                        dialog.dismiss();
                        dismiss();
                        ToastUtils.showToast(activity, "您的账号已在其他设备登录，请重新登陆");
                        activity.startActivity(new Intent(activity, LoginActivity.class));
                    } else {
                        dialog.dismiss();
                        ToastUtils.showToast(activity, "支付出错");
                    }
                } else {
                    dialog.dismiss();
                    ToastUtils.showToast(activity, "支付出错");
                }


            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();

            }

            @Override
            public void onError(String error) {
                super.onError(error);
                ToastUtils.showToast(activity, "支付出错");
            }
        });
    }

}
